package com.piece.mall.service;

import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.mall.model.PmsAttrGroupRelation;
import com.piece.mall.repository.PmsAttrGroupRelationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class PmsAttrGroupRelationService extends BaseService<PmsAttrGroupRelation, String> {

    @Autowired
    private PmsAttrGroupRelationRepository pmsAttrGroupRelationRepository;

    @PostConstruct
    public void initRepository() {
        setRepository(pmsAttrGroupRelationRepository);
    }

    public void saveRelation(Long groupId, Long[] attrIds) {
        // 清空历史所有数据
        pmsAttrGroupRelationRepository.deleteByProperties("attrGroupId", groupId);
        List<PmsAttrGroupRelation> relationList = new ArrayList<>();
        for (int i = 1; i <= attrIds.length; i++) {
            PmsAttrGroupRelation relation = new PmsAttrGroupRelation();
            relation.setAttrGroupId(groupId);
            relation.setAttrId(attrIds[i - 1]);
            relation.setAttrSort(Convert.toLong(i));
            relationList.add(relation);
        }
        pmsAttrGroupRelationRepository.batchInsert(relationList);
    }

    public int deleteRelationByGroupId(Long groupId, Long[] attrIds) {
        String sql = "delete from pms_attr_group_relation where attr_group_id=?0 and attr_id in(?1)";
        return pmsAttrGroupRelationRepository.deleteByProperties(MapUtil.builder(new HashMap<String, Object>())
                .put("Q_attrGroupId_L_EQ", groupId).put("Q_attrId_L_IN", Arrays.asList(attrIds)).build());
    }
}
